package org.dromara.oce.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bytedance.ads.model.AgentAdvertiserInfoQueryV2ResponseDataAccountDetailListInner;
import com.bytedance.ads.model.ProjectCreateV30MicroPromotionType;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.ObjectUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.oce.domain.OceTemplateTask;
import org.dromara.oce.domain.bo.OceTemplateTaskAddBo;
import org.dromara.oce.domain.bo.OceTemplateTaskBo;
import org.dromara.oce.domain.dto.ProjectPromotionAggregation;
import org.dromara.oce.domain.qo.OceTemplateTaskQo;
import org.dromara.oce.domain.req.ProjectCreateV30Request2;
import org.dromara.oce.domain.req.CreatePromotionV3Request;
import org.dromara.oce.domain.vo.OceTemplateTaskVo;
import org.dromara.oce.mapper.OceTemplateTaskMapper;
import org.dromara.oce.service.OceTemplateTaskService;
import org.dromara.oce.service.remote.OceanEngineThirdRemoteService;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.List;

/**
 * 巨量项目广告任务记录Service业务层处理
 *
 * @author dsbb
 * @date 2025-07-04
 */
@RequiredArgsConstructor
@Service
@Slf4j
public class OceTemplateTaskServiceImpl extends ServiceImpl<OceTemplateTaskMapper, OceTemplateTask> implements OceTemplateTaskService {

    private final OceTemplateTaskMapper baseMapper;
    private final OceanEngineThirdRemoteService oceanEngineThirdRemoteService;

    /**
     * 查询巨量项目广告任务记录
     *
     * @param taskId 主键
     * @return 巨量项目广告任务记录
     */
    @Override
    public OceTemplateTaskVo queryById(Long taskId) {
        OceTemplateTaskVo taskVo = baseMapper.selectVoById(taskId);

        List<AgentAdvertiserInfoQueryV2ResponseDataAccountDetailListInner> list = oceanEngineThirdRemoteService.getAdvertiserInfo(taskVo.getAccountId(), Arrays.asList(taskVo.getAdvertiserId()));
        if (list != null && list.size() > 0) {
            taskVo.setAdvertiserName(list.get(0).getAdvertiserName());
        }
        return taskVo;
    }

    /**
     * 分页查询巨量项目广告任务记录列表
     *
     * @param qo        查询条件
     * @param pageQuery 分页参数
     * @return 巨量项目广告任务记录分页列表
     */
    @Override
    public TableDataInfo<OceTemplateTaskVo> queryPageList(OceTemplateTaskQo qo, PageQuery pageQuery) {
        LambdaQueryWrapper<OceTemplateTask> lqw = buildQueryWrapper(qo);
        Page<OceTemplateTaskVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询符合条件的巨量项目广告任务记录列表
     *
     * @param qo 查询条件
     * @return 巨量项目广告任务记录列表
     */
    @Override
    public List<OceTemplateTaskVo> queryList(OceTemplateTaskQo qo) {
        LambdaQueryWrapper<OceTemplateTask> lqw = buildQueryWrapper(qo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<OceTemplateTask> buildQueryWrapper(OceTemplateTaskQo qo) {
        LambdaQueryWrapper<OceTemplateTask> lqw = Wrappers.lambdaQuery();
//        lqw.eq(OceTemplateTask::getAccountId,qo.getAccountId());
        lqw.like(!ObjectUtils.isEmpty(qo.getDramaTitle()), OceTemplateTask::getDramaTitle, qo.getDramaTitle());
        lqw.eq(!ObjectUtils.isEmpty(qo.getAdvertiserId()), OceTemplateTask::getAdvertiserId, qo.getAdvertiserId());
        lqw.like(!ObjectUtils.isEmpty(qo.getName()), OceTemplateTask::getName, qo.getName());
        lqw.eq(!ObjectUtils.isEmpty(qo.getCreateName()), OceTemplateTask::getCreateName, qo.getCreateName());
        lqw.orderByDesc(OceTemplateTask::getTaskId);
        return lqw;
    }


    @Override
    public Boolean insertByBo(OceTemplateTaskAddBo req) {
        for (ProjectPromotionAggregation promotionAggregation : req.getProjectPromotionList()) {
            OceTemplateTask oceTemplateTask = new OceTemplateTask();
            oceTemplateTask.setAccountId(req.getAccountId());
            oceTemplateTask.setAdvertiserId(promotionAggregation.getAdvertiserId());
            //投手名
            oceTemplateTask.setCreateName(req.getName());
            String subStr = "";
            if (req.getSubmitType() == 0) {
                subStr = "立即提交";
            } else if (req.getSubmitType() == 1) {
                subStr = "异步提交";
            } else if (req.getSubmitType() == 2) {
                subStr = "定时提交";
            }
            oceTemplateTask.setSubmitType(req.getSubmitType());
            try {
                oceTemplateTask.setName(req.getName() + "_新建广告_" + subStr + "_" + DateUtil.format(new Date(), "MM_dd_HH:mm:ss"));
                ProjectCreateV30MicroPromotionType microPromotionType = promotionAggregation.getProjectList().get(0).getMicroPromotionType();
                if (ProjectCreateV30MicroPromotionType.WECHAT_APP.equals(microPromotionType)) {
                    oceTemplateTask.setPromotionType("微信小程序");
                } else if (ProjectCreateV30MicroPromotionType.BYTE_APP.equals(microPromotionType)) {
                    oceTemplateTask.setPromotionType("字节小程序");
                } else if (ProjectCreateV30MicroPromotionType.AWEME.equals(microPromotionType)) {
                    oceTemplateTask.setPromotionType("抖音号");
                }
                oceTemplateTask.setDramaTitle(promotionAggregation.getProjectList().get(0).getPromotionList().get(0).getPromotionMaterials().getProductInfo().getTitles().get(0));
            } catch (Exception e) {
            }

            oceTemplateTask.setProjectJson(req.getProjectJson());
            oceTemplateTask.setProjectNum(promotionAggregation.getProjectList().size());
            oceTemplateTask.setPromotionNum(0);
            oceTemplateTask.setPushTime(req.getPushTime());
            oceTemplateTask.setProjectPromotionJson(JSONUtil.toJsonStr(promotionAggregation));
//            oceTemplateTask.setRemark("");

            if (req.getSubmitType() != 2) {
                this.save(oceTemplateTask);

                StringBuffer projectErrorMsg = new StringBuffer();
                StringBuffer promotionErrorMsg = new StringBuffer();

                int promotionTotalNum = 0;
                int successNum = 0;
                for (int projectNum = 0; projectNum < promotionAggregation.getProjectList().size(); projectNum++) {
                    ProjectCreateV30Request2 project = promotionAggregation.getProjectList().get(projectNum);
                    try {
                        promotionTotalNum = promotionTotalNum + project.getPromotionList().size();

                        Long projectId = project.getProjectId();
                        if(ObjectUtils.isEmpty(projectId)){
                            projectId = oceanEngineThirdRemoteService.createProject(req.getAccountId(), project);
                        }

                        for (int adNum = 0; adNum < project.getPromotionList().size(); adNum++) {
                            try {
                                CreatePromotionV3Request promotionV3Request = project.getPromotionList().get(adNum);
                                promotionV3Request.setProjectId(projectId);
                                oceanEngineThirdRemoteService.createPromotion(req.getAccountId(), promotionV3Request);
                                successNum = successNum + 1;
                            } catch (Exception e) {
                                promotionErrorMsg.append("项目id=" + projectId + ",广告序号：" + adNum + ",错误信息：" + e.getMessage());
                            }
                        }
                    } catch (Exception e) {
                        log.info("创建项目失败，第{}个项目,{}", projectNum + 1, e.getMessage());
                        projectErrorMsg.append("创建第" + (projectNum + 1) + "个项目失败，" + e.getMessage());
                    }
                }
                oceTemplateTask.setExecuteStatus(1);
                oceTemplateTask.setPromotionNum(promotionTotalNum);
                oceTemplateTask.setRemark(projectErrorMsg.toString() + "  ||| " + promotionErrorMsg.toString());
                oceTemplateTask.setSuccessNum(successNum);
                oceTemplateTask.setFailNum(promotionTotalNum - successNum);
                this.updateById(oceTemplateTask);
            } else {
                int promotionTotalNum = 0;
                for (int projectNum = 0; projectNum < promotionAggregation.getProjectList().size(); projectNum++) {
                    ProjectCreateV30Request2 project = promotionAggregation.getProjectList().get(projectNum);
                    promotionTotalNum = promotionTotalNum + project.getPromotionList().size();
                }
                oceTemplateTask.setPromotionNum(promotionTotalNum);
                this.save(oceTemplateTask);
            }
        }
        return true;
    }

    /**
     * 修改巨量项目广告任务记录
     *
     * @param bo 巨量项目广告任务记录
     * @return 是否修改成功
     */
    @Override
    public Boolean updateByBo(OceTemplateTaskBo bo) {
        OceTemplateTask update = MapstructUtils.convert(bo, OceTemplateTask.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(OceTemplateTask entity) {
    }

    /**
     * 校验并批量删除巨量项目广告任务记录信息
     *
     * @param ids     待删除的主键集合
     * @param isValid 是否进行有效性校验
     * @return 是否删除成功
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
        }
        return baseMapper.deleteByIds(ids) > 0;
    }

    @Override
    public void executeTask() {
        LambdaQueryWrapper<OceTemplateTask> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(OceTemplateTask::getSubmitType, 2);
        lambdaQueryWrapper.eq(OceTemplateTask::getExecuteStatus, 0);
        lambdaQueryWrapper.le(OceTemplateTask::getPushTime, LocalDateTime.now());
        List<OceTemplateTask> list = this.list(lambdaQueryWrapper);
        if (list == null || list.size() == 0) {
            log.info("没有查询到待执行的广告任务");
            return;
        }
        log.info("查询待执行的任务条数：{}", list.size());
        for (OceTemplateTask oceTemplateTask : list) {
            try {
                JSONObject jsonObject = JSONObject.parseObject(oceTemplateTask.getProjectPromotionJson());
                ProjectPromotionAggregation promotionAggregation = BeanUtil.copyProperties(jsonObject, ProjectPromotionAggregation.class);

                StringBuffer projectErrorMsg = new StringBuffer();
                StringBuffer promotionErrorMsg = new StringBuffer();

                int promotionTotalNum = 0;
                int successNum = 0;
                for (int projectNum = 0; projectNum < promotionAggregation.getProjectList().size(); projectNum++) {
                    ProjectCreateV30Request2 project = promotionAggregation.getProjectList().get(projectNum);
                    try {
                        promotionTotalNum = promotionTotalNum + project.getPromotionList().size();
                        Long projectId = oceanEngineThirdRemoteService.createProject(oceTemplateTask.getAccountId(), project);

                        for (int adNum = 0; adNum < project.getPromotionList().size(); adNum++) {
                            try {
                                CreatePromotionV3Request promotionV3Request = project.getPromotionList().get(adNum);
                                promotionV3Request.setProjectId(projectId);
                                oceanEngineThirdRemoteService.createPromotion(oceTemplateTask.getAccountId(), promotionV3Request);
                                successNum = successNum + 1;
                            } catch (Exception e) {
                                promotionErrorMsg.append("项目id=" + projectId + ",广告序号：" + adNum + ",错误信息：" + e.getMessage());
                            }
                        }
                    } catch (Exception e) {
                        log.info("创建项目失败，第{}个项目,{}", projectNum + 1, e.getMessage());
                        projectErrorMsg.append("创建第" + (projectNum + 1) + "个项目失败，" + e.getMessage());
                    }
                }
                oceTemplateTask.setExecuteStatus(1);
                oceTemplateTask.setPromotionNum(promotionTotalNum);
                oceTemplateTask.setRemark(projectErrorMsg.toString() + "  ||| " + promotionErrorMsg.toString());
                oceTemplateTask.setSuccessNum(successNum);
                oceTemplateTask.setFailNum(promotionTotalNum - successNum);
                this.updateById(oceTemplateTask);
            } catch (Exception e) {
                log.info("广告主：{}，创建广告发送异常，{}",oceTemplateTask.getAdvertiserId(),e.getMessage());
            }
        }
    }
}
